package com.wanlian.router.ui.manage;

import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;
import com.smart.android.ui.BaseActivity;
import com.smart.android.ui.web.WebActivity;
import com.wanlian.router.R;
import com.wanlian.router.app.AppConfig;
import com.wanlian.router.bean.ShareDisk;
import com.wanlian.router.bean.WifiSetting;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.internal.INetCallBack;
import com.wanlian.router.storage.AppData;

import java.util.ArrayList;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Hyu on 2018/9/4.
 * Email: fvaryu@163.com
 */
public class ShareDiskManageActivity extends BaseActivity {

    @BindView(R.id.piechart)
    PieChart mChart;
    @BindView(R.id.tv_size)
    EditText mSize;
    @BindView(R.id.tv_help)
    TextView tv_help;
    @BindView(R.id.tv_num)
    TextView tv_num;
    private int sizeInt;

    private  int total;

    @Override
    protected int layout() {
        return R.layout.activity_share_disk;
    }

    @Override
    public void initUI() {
        super.initUI();
        setTitle("共享磁盘管理");

        tv_help.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
    }

    @Override
    public void initData() {
        super.initData();

        NetWorkingClient.getInstance().querySharedDisk(getActivity(), new INetCallBack<ShareDisk>() {
            @Override
            public void onFinish(ResponseData response, @Nullable ShareDisk shareDisk) {
                if (response.isSuccess()) {
                    mChart.setVisibility(View.VISIBLE);
                    if (shareDisk == null) {
                        chartDefault();
                        return;
                    }
                    sizeInt = shareDisk.getShare();
                    total = (int)shareDisk.getSum();
                    mSize.setText(String.format(Locale.getDefault(), "%dG", sizeInt));
                    tv_num.setText(String.format(Locale.getDefault(), "总计：%.0fG\n共享：%dG", shareDisk.getSum(), sizeInt));

                    setData(sizeInt, (total == 0) ? 100.f : (float) total);

                } else {
                    showToast(response.getMessage());
                }
            }
        });

        mChart.setDrawMarkers(false);
        mChart.setUsePercentValues(true);
        mChart.getDescription().setEnabled(false);
        mChart.setExtraOffsets(5, 10, 5, 5);

        mChart.setDragDecelerationFrictionCoef(0.95f);


        mChart.setCenterText("");

        mChart.setDrawHoleEnabled(true);
        mChart.setHoleColor(Color.WHITE);

        mChart.setTransparentCircleColor(Color.WHITE);
        mChart.setTransparentCircleAlpha(110);

        mChart.setHoleRadius(80f);
        mChart.setTransparentCircleRadius(43f);

        mChart.setDrawCenterText(false);

        mChart.setRotationAngle(-90);
        // enable rotation of the chart by touch
        mChart.setRotationEnabled(false);
        mChart.setHighlightPerTapEnabled(false);

        // mChart.setUnit(" €");
        // mChart.setDrawUnitsInChart(true);

        // add a selection listener


        Legend l = mChart.getLegend();
        l.setEnabled(false);

        // entry label styling
        mChart.setEntryLabelColor(Color.WHITE);
        mChart.setEntryLabelTextSize(12f);


        mSize.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String size = mSize.getText().toString().replace("G", "");
                int sizeA = 0;
                try {
                    sizeA = Integer.parseInt(size);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                if (sizeA < 0) {
                    sizeInt = 0;
                    mSize.setText(String.format(Locale.getDefault(), "%dG", sizeInt));
                }
//                int a = (int) (mWifiSetting.getDMemory() + mWifiSetting.getWMemory());
//                if (sizeA > a) {
//                    sizeInt = a;
//                    mSize.setText(String.format(Locale.getDefault(), "%dG", sizeInt));
//                }


            }
        });
    }

    private void chartDefault() {
        mSize.setText(String.format(Locale.getDefault(), "%dG", 0));
        tv_num.setText(String.format(Locale.getDefault(), "总计：%.0fG\n共享：%.0fG", 100, 0));

        setData(0, 100);
    }


    @OnClick(R.id.tv_decrease)
    void decrease() {
        if (sizeInt <= 0) {
            return;
        }
        sizeInt--;
        mSize.setText(String.format(Locale.getDefault(), "%dG", sizeInt));
    }

    @OnClick(R.id.tv_increase)
    void increase() {
        sizeInt++;

        if (sizeInt > total) {
            sizeInt = total;
        }
        mSize.setText(String.format(Locale.getDefault(), "%dG", sizeInt));
    }

    private void setData(float shared, float total) {

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();

        // NOTE: The order of the entries when being added to the entries array determines their position around the center of
        // the chart.
        entries.add(new PieEntry(total,
                "a",
                getResources().getDrawable(R.drawable.ic_def_filepic)));
        entries.add(new PieEntry(shared,
                "a",
                getResources().getDrawable(R.drawable.ic_def_filepic)));

        PieDataSet dataSet = new PieDataSet(entries, "Election Results");

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);

        // add a lot of colors
        dataSet.setColors(getColorById(R.color.color_blue), Color.parseColor("#21D7F2"));


//        dataSet.setSelectionShift(0f);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(0f);
        data.setValueTextColor(Color.WHITE);
        data.setDrawValues(false);

        mChart.setData(data);
        mChart.setDrawEntryLabels(false);

        Highlight[] highlights = new Highlight[1];
        highlights[0] = new Highlight(0, 0, 0);
        mChart.highlightValues(highlights);

        mChart.invalidate();


    }

    private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda");
        s.setSpan(new RelativeSizeSpan(1.7f), 0, 14, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }

    @OnClick(R.id.tv_next)
    void next() {
        String size = mSize.getText().toString().replace("G", "");
        int sizeA = 0;
        try {
            sizeA = Integer.parseInt(size);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        NetWorkingClient.getInstance().addShareDisk(getActivity(), sizeA, new INetCallBack() {
            @Override
            public void onFinish(ResponseData response, @Nullable Object o) {
                if (response.isSuccess()) {
                    showToast("设置成功");
                    finish();
                } else {
                    showToast(response.getMessage());
                }
            }
        });
    }

    @OnClick(R.id.tv_help)
    void help() {
        WebActivity.fire(this, AppData.DEFAULT.get(AppConfig.DISK_HELP));
    }
}
